package com.lottery.ruok.lottrey.adapter

import android.support.v7.widget.RecyclerView
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import com.lottery.ruok.lottrey.R

class LHCQuickEditAmountAdapter(val items : List<String>, private val listenEdit: (String, Int)->Unit): RecyclerView.Adapter<LHCQuickEditAmountAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.lhc_quick_edit_item_layout, parent, false)
        return ViewHolder(view, listenEdit)
    }

    override fun getItemCount(): Int = items.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(items.elementAt(position), position)
    }

    class ViewHolder(val view: View, val listenEdit: (String, Int) -> Unit) : RecyclerView.ViewHolder(view) {
        fun bind(news: String, position: Int) {
            val editText: EditText = view.findViewById(R.id.option_text)
            editText.setText(news)
            editText.setOnFocusChangeListener { view, b ->
                if (b) {// 获得焦点
                    editText.postDelayed({
                        editText.setSelection(editText.text.toString().length)
                    }, 100)
                }
            }
            editText.addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(p0: Editable?) {
                    listenEdit.invoke(p0.toString(), position)
                }

                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }
            })
        }
    }
}